﻿using System;

namespace BuzzX8.Xmpp
{
    public class XmlNamespace
    {
        private string name;
        private string uri;

        public XmlNamespace() : this(string.Empty, string.Empty)
        {
        }

        public XmlNamespace(string uri) : this(string.Empty, uri)
        {
        }

        public XmlNamespace(string name, string uri)
        {
            if (!string.IsNullOrEmpty(name) && !IsValidNamespaceName(name)) throw new ArgumentException("Invalid name for XML namespace");
            if(!string.IsNullOrEmpty(name) && string.IsNullOrEmpty(uri)) throw new ArgumentException("", "uri");
            this.name = name;
            this.uri = uri;
        }

        private bool IsValidNamespaceName(string name)
        {
            return name.IndexOfAny(new[] {':'}) < 0;
        }

        public string Name
        {
            get { return name; }
        }

        public string Uri
        {
            get { return uri; }
        }

        public bool IsEmpty
        {
            get { return string.IsNullOrEmpty(name) && string.IsNullOrEmpty(uri); }
        }

        public override string ToString()
        {
            return Uri;
        }

        public static implicit operator string(XmlNamespace xmlNamespace)
        {
            return xmlNamespace.Uri;
        }

        public static implicit operator XmlNamespace(string namespaceUri)
        {
            return new XmlNamespace("", namespaceUri);
        }

        public override bool Equals(object obj)
        {
            if (!(obj is XmlNamespace)) return false;
            XmlNamespace ns = (XmlNamespace) obj;
            return Uri == ns.Uri && Name == ns.Name;
        }
    }
}
